﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Core.Sdk.WeiXin.Tool
{
    public class JsonHttp
    {

        protected static HttpClient CreateHttpClient(HttpHandler hander)
        {
            HttpClient client = new HttpClient(hander);
            client.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
            client.DefaultRequestHeaders.Add("Accept", @"application/json");
            return client;
        }

        /// <summary>
        /// Get请求数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string Get(string url, HttpHandler hander)
        {
            var httpClient = CreateHttpClient(hander);
            var res = httpClient.GetAsync(url).Result;
            if (res.IsSuccessStatusCode)
            {
                Task<string> t = res.Content.ReadAsStringAsync();
                return t.Result;
            }
            else
            {
                Task<string> t = res.Content.ReadAsStringAsync();
                Console.WriteLine(t.Result);
            }
            return string.Empty;
        }

        public static T Get<T>(string url, HttpHandler hander)
        {
            var json = Get(url, hander);
            if (string.IsNullOrEmpty(json))
                return default(T);
            return JsonConvert.DeserializeObject<T>(json);
        }

        public static string Post(string url, string postData, HttpHandler hander)
        {
            var httpClient = CreateHttpClient(hander);
            var content = new StringContent(postData);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var res = httpClient.PostAsync(url, content).Result;
            if (res.IsSuccessStatusCode)
            {
                Task<string> t = res.Content.ReadAsStringAsync();
                return t.Result;
            }
            else
            {
                Task<string> t = res.Content.ReadAsStringAsync();
                Console.WriteLine(t.Result);
            }
            return string.Empty;
        }

    }
}
